package za.co.dylanjaneke.airdownloader.model.vo
{
	import com.adobe.utils.DateUtil;
	
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	import flash.events.SQLEvent;
	
	import mx.collections.ArrayCollection;

	/**
	 * Author: Dylan Janeke.
	 */
	[Bindable]
	public class LogEntryVO implements DBVO
	{
		public var id:Number;
		public var date:Date;
		private var _level:Number;
		public var message:String;
		public var location:String;
		
		public function get level():String
		{
			if(_level==0)
			{
				return "INFO";
			}
			if(_level==1)
			{
				return "WARN";
			}
			if(_level==2)
			{
				return "ERROR";
			}
			if(_level==3)
			{
				return "PANIC";
			}
			if(_level==4)
			{
				return "DEBUG";
			}
			return null;
		}
		
		public function set level(lev:String):void
		{
			if(lev=="INFO")
			{
				_level=0;
				return;
			}
			if(lev=="WARN")
			{
				_level=1;
				return;
			}
			if(lev=="ERROR")
			{
				_level=2;
				return;
			}
			if(lev=="PANIC")
			{
				_level=3;
				return;
			}
			if(lev=="DEBUG")
			{
				_level=4;
				return;
			}
		}
		
		public function LogEntryVO(date:Date=null, level:String=null, message:String=null, location:String=null,id:Number=NaN)
		{
			this.date= date;
			this.level= level;
			this.message= message;
			this.location= location;
			this.id= id;
		}
		
		/*
		public var id:Number;
		public var date:Date;
		private var _level:Number;
		public var message:String;
		public var location:String;
		*/
		public function get createQuery():String
		{
			return "CREATE TABLE IF NOT EXISTS ad_log (id INTEGER PRIMARY KEY AUTOINCREMENT, " +
				"dte TEXT, level INTEGER, message TEXT, location TEXT);";
		}
		
		public static function valueOf(event:SQLEvent): ArrayCollection
		{
			var statement:SQLStatement=
				event.currentTarget as SQLStatement;
			var result:SQLResult= statement.getResult();
			if(result==null||result.data==null)
				return null;
			
			var col:ArrayCollection= new ArrayCollection();
			
			for each(var row:Object in result.data)
			{
				var vo:LogEntryVO= new LogEntryVO
				(
					DateUtil.parseW3CDTF(row.dte),
					row.level, row.message, row.location, row.id
				);
				col.addItem(vo);
			}
			
			return col;
		}
		
		public static function createInsert(vo:LogEntryVO, statement:SQLStatement): SQLStatement
		{
			statement.text= "INSERT INTO ad_log (dte,level,message,location) VALUES "+
				"(:dte,:lev,:mes,:loc)";
			statement.parameters[":dte"]= DateUtil.toW3CDTF(vo.date, true);
			statement.parameters[":lev"]= vo._level;
			statement.parameters[":mes"]= vo.message;
			statement.parameters[":loc"]= vo.location;
			
			return statement;
		}
		
		public function toString():String
		{
			return "["+this.date+"] " + this.location + " ["+this.level+"] " + this.message;
		}
	}
}